package com.buer.dao.util.db;

import org.apache.commons.collections.MapUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 〈sql模板〉
 */
public class SqlSessionExecutor extends SqlSessionTemplate {

    /**
     * 构造函数
     */
    public SqlSessionExecutor(SqlSessionFactory sqlSessionFactory) {
        super(sqlSessionFactory);
    }

    /**
     * 根据Limit查询一段数据， 分页查询谨慎使用
     */
    public Object selectListByLimitNoPage(String statement, Object parameter, Limit limit) {
        int offset = limit.getRowStart();
        int pageSize = limit.getPageSize();

        // 设置分页边界，并查询结果集
        RowBounds bound = new RowBounds(offset, pageSize);
        return selectList(statement, parameter, bound);
    }

    /**
     * 根据分页条件，查询结果集
     */
    public Object selectPage(String statement, Object parameter, Limit limit) {

        // 查询分页内容
        PageResultEntity pageResultEntity = selectPageWithCnt(statement, parameter, limit);
        return pageResultEntity.getDataList();
    }

    /**
     * 根据分页条件，查询结果集
     */
    public PageResultEntity selectPageWithCnt(String statement, Object parameter, Limit limit) {

        // 设置符合条件的结果集总数
        List<BaseEntity> resultForCount = super.selectList(statement, parameter, new RowBounds(-1, -1));

        Integer resultCount = resultForCount.get(0).getTotalCount();
        int totalCount = resultCount.intValue();
        limit.setTotalRecords(totalCount);

        int offset = limit.getRowStart();
        int pageSize = limit.getPageSize();

        RowBounds bound = null;
        if (totalCount < (offset + pageSize)) {
            bound = new RowBounds(offset, totalCount - offset);
        } else {
            bound = new RowBounds(offset, pageSize);
        }

        // 查询分页内容
        List<Object> dataList = selectList(statement, parameter, bound);

        // 构造结果（total dataList）
        PageResultEntity result = new PageResultEntity();
        result.setTotalCount(resultCount);
        result.setDataList(dataList);
        return result;
    }
}
